package com.example.administrator.hqq.fragment.discover;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.layout.EmptyLayout;
import com.example.administrator.hqq.activity.group.CreateGroupChatActivity;
import com.example.administrator.hqq.activity.group.JoinGroupActivity;
import com.example.administrator.hqq.adapter.discover.ConvenGroupListAdapter;
import com.example.administrator.hqq.base.MyFragemnt;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.GroupEvent;
import com.example.administrator.hqq.bean.group.GroupListBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 * 群聊列表页面
 */
public class GroupChatListFragment extends MyFragemnt {


    Unbinder unbinder;
    @BindView(R.id.group_list_et)
    TextView groupListEt;
    @BindView(R.id.create_group)
    ImageView createGroup;
    @BindView(R.id.group_search_button)
    ImageView groupSearchButton;
    @BindView(R.id.group_search)
    AutoRelativeLayout groupSearch;
    @BindView(R.id.navigation_bar)
    AutoRelativeLayout navigationBar;
    @BindView(R.id.group_lv)
    ListView groupLv;
    @BindView(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private float y1 = 0;
    private float y2 = 0;
    private int page = 1;
    private String amount = "20";
    private List<GroupListBean.DataBean> data;
    private Boolean isRefresh = false;
    private String TAG = this.getClass().getSimpleName();
    private String last_id = "";
    private ConvenGroupListAdapter convenGroupListAdapter;
    private String gender_prefer = "0";
    private String city_prefer = "0";
    private String age_prefer = "0";
    private String topic_id = "";
    private int mTouchSlop;//系统认为的最小滑动距离
    private float mFirstY;//用户首次触摸的Y坐标
    private float mLastY;//用户滑动结束时Y坐标
    private ObjectAnimator mAnimator;//将控件与动画联系起来的类（可以使指定的控件，实现指定的动画效果）
    private boolean mShow = true;//toolbar是否显示
    private AlertDialog showReportAlertView;
    private AnimatorSet animatorSet;

    public GroupChatListFragment() {
        // Required empty public constructor
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_group_chat_list, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        EventBus.getDefault().register(this);
        initview();
        return inflate;
    }

    private void initdata() {
        if (page == 1 || data.size() <= 0) {
            last_id = "";
        } else {
            last_id = data.get(data.size() - 1).getId();
        }
        OkHttpUtils.get().url(UrlFactory.getGroupList()).tag(this)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.topic_id, topic_id)
                .addParams(LoongsConfig.gender_prefer, gender_prefer)
                .addParams(LoongsConfig.city_prefer, city_prefer)
                .addParams(LoongsConfig.age_prefer, age_prefer)
                .addParams(LoongsConfig.key_word, "")
                .addParams(LoongsConfig.page, page + "")
                .addParams(LoongsConfig.amount, amount)
                .addParams(LoongsConfig.last_id, last_id)
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                if (emptyLayout != null)
                    emptyLayout.showEmpty();
                if (refreshLayout != null) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                dismissLoadingDialog();
                Log.e(TAG, "onResponse: " + response);
                Gson gson = new Gson();
                GroupListBean groupListBean = gson.fromJson(response, GroupListBean.class);
                if (groupListBean.getData() != null && groupListBean != null && groupListBean.getCode() == 200) {
                    if (page == 1) {
                        if (groupListBean.getData() == null || groupListBean.getData().size() == 0) {
                            emptyLayout.showEmpty();
                        }else{
                            emptyLayout.hide();
                        }
                        data.clear();
                    }
                    data.addAll(groupListBean.getData());
                    convenGroupListAdapter.notifyDataSetChanged();
                }
                if (refreshLayout != null) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initview() {
//        connect("xiYuj5fs7WV6dgsBsXuyhBipd+siNC7nu6z5uiapBeAx5u/QplDSBtZ3mQNQgCFGoZo88ZWls+tlaoObrPtlbA==");
        data = new ArrayList<>();
        //初始化适配器
//        setScroll();
//        final View headView = new View(getContext());
//        groupSearch.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                groupSearch.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//                headView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT,
//                        groupSearch.getMeasuredHeight()));
//                headView.setBackgroundColor(Color.parseColor("#FFFCF9"));
//                groupLv.addHeaderView(headView);
//            }
//        });
        convenGroupListAdapter = new ConvenGroupListAdapter(data, getContext());
        groupLv.setAdapter(convenGroupListAdapter);
        convenGroupListAdapter.setOnClickListener(new ConvenGroupListAdapter.OnClickListener() {
            @Override
            public void informClick(final int position1) {
                List<String> strings = new ArrayList<>();
                for (String s : getContext().getResources().getStringArray(R.array.group_report)) {
                    strings.add(s);
                }
                showReportAlertView = AlertViewFactory.getInstance().getShowReportAlertView(getContext(), strings, new AlertViewFactory.ReportOnClickListener() {
                    @Override
                    public void submit(int position) {
                        Log.e(TAG, "submit: " + position);
                        showReportAlertView.cancel();
                        reportGroup(position, position1);
                    }
                });
            }

            @Override
            public void joinGroupClick(int position) {
                joinGroupCheck(position);
            }
        });
        //设置刷新动画
        refreshLayout.setEnableAutoLoadMore(true);
//        refreshLayout.setRefreshHeader(new BezierCircleHeader(getContext()));
        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
//       设置滚动监听
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //下拉刷新
                page = 1;
                initdata();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                //上拉加载
                page = page + 1;
                initdata();
            }
        });
    }

    /**
     * 举报群聊
     *
     * @param position  举报项的下标
     * @param position1 举报的帖子的下标
     */
    private void reportGroup(int position, int position1) {
        OkHttpUtils.get().url(UrlFactory.ReportForum())
                .addParams(LoongsConfig.id, data.get(position1).getId())
                .addParams(LoongsConfig.type, "3")
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reason_id, position + 401 + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "举报群聊onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "举报群聊onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        data.remove(position1);
        convenGroupListAdapter.notifyDataSetChanged();
    }

    /**
     * 进群检测
     *
     * @param position
     */
    private void joinGroupCheck(final int position) {
        OkHttpUtils.get().url(UrlFactory.getGroupCheck())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.group_id, data.get(position).getId())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "进群检测onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    String description = jsonObject.getString("description");
                    HintWordsUtils.showMarkeWords(code, description);
                    SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.GROUP);
                    SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ConversationID, data.get(position).getId());
                    switch (code) {
                        case 200:
                        case 201:
                            RongIM.getInstance().startConversation(getContext(), Conversation.ConversationType.GROUP, data.get(position).getId(), "话圈圈");
                            break;
                        case 202:
                            Intent intent = new Intent(getContext(), JoinGroupActivity.class);
                            intent.putExtra(LoongsConfig.group_id, data.get(position).getId());
                            startActivity(intent);
                            break;
                        case 203:
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(GroupEvent groupEvent) {
        switch (groupEvent.getType()) {
            case DELETE_GROUP:
                page = 1;
                initdata();
                break;
            case CREATE_GROUP:
                page = 1;
                initdata();
                break;
            case ALTER_GROUP:
                page = 1;
                initdata();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Complain complain) {
        switch (complain.getType()) {
            case JOIN_GROUP:
                page = 1;
                initdata();
                break;
            case QUIT_GROUP:
                page = 1;
                initdata();
                break;
            case KICK_MEMBER:
                page = 1;
                initdata();
                break;
            case DIRECTCHAT:
                page = 1;
                initdata();
                break;
        }
    }

    private int mLastFirstPostion;
    private int mLastFirstTop;
    private int touchSlop;

    private void setScroll() {
//        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
//        //为ListView设置触摸事件监听
//        groupLv.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        mFirstY = event.getY();//getY获取的是相对于View的坐标，getRawY获取的是相对于屏幕的坐标
//                        Log.e("tag", "mFirstY: " + mFirstY);
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        mLastY = event.getY();
//                        Log.e("tag", "onTouch: " + mLastY + "++++++" + mFirstY);
//                        if (mLastY - mFirstY > mTouchSlop) {//手指向下滑动，显示toolbar
//                            if (!mShow) {
//                                Log.i("tag", "mLastY_手指下滑=" + mLastY);
//                                toolbarAnim(0);//显示
//                                mShow = !mShow;
//                            }
//                        } else if (mFirstY - mLastY > mTouchSlop) {//手指向上滑动，隐藏toolbar
//                            if (mShow) {
//                                Log.i("tag", "mLastY_手指上滑=" + mLastY);
//                                toolbarAnim(1);//隐藏
//                                mShow = !mShow;
//                            }
//                        }
//                        mFirstY = mLastY;
//                        break;
//                    default:
//                        break;
//                }
//                return false;//一般返回false，提交给上级
//            }
//        });
        groupLv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int currentTop;

                View firstChildView = absListView.getChildAt(0);
                if (firstChildView != null) {
                    currentTop = absListView.getChildAt(0).getTop();
                } else {
                    //ListView初始化的时候会回调onScroll方法，此时getChildAt(0)仍是为空的
                    return;
                }
                //判断上次可见的第一个位置和这次可见的第一个位置
                if (firstVisibleItem != mLastFirstPostion) {
                    //不是同一个位置
                    if (firstVisibleItem > mLastFirstPostion) {
                        //TODO do down
                        Log.i("cs", "--->down");
                        if (mShow) {
                            toolbarAnim(1);//隐藏
                            mShow = !mShow;
                        }
                    } else {
                        //TODO do up
                        Log.i("cs", "--->up");
                        if (!mShow) {
                            toolbarAnim(0);//显示
                            mShow = !mShow;
                        }
                    }
                    mLastFirstTop = currentTop;
                } else {
                    //是同一个位置
                    if (Math.abs(currentTop - mLastFirstTop) > touchSlop) {
                        //避免动作执行太频繁或误触，加入touchSlop判断，具体值可进行调整
                        if (currentTop > mLastFirstTop) {
                            //TODO do up
                            Log.i("cs", "equals--->up");
                            if (!mShow) {
                                toolbarAnim(0);//显示
                                mShow = !mShow;
                            }
                        } else if (currentTop < mLastFirstTop) {
                            //TODO do down
                            Log.i("cs", "equals--->down");
                            if (mShow) {
                                toolbarAnim(1);//隐藏
                                mShow = !mShow;
                            }
                        }
                        mLastFirstTop = currentTop;
                    }
                }
                mLastFirstPostion = firstVisibleItem;
            }
        });
    }

    public void toolbarAnim(int flag) {
        if (mAnimator != null && mAnimator.isRunning()) {
            mAnimator.cancel();
        }
        if (flag == 0) {
            Log.i("tag", "手指下滑,》》》》》》》显示");
            mAnimator = ObjectAnimator.ofFloat(groupSearch, "translationY", groupSearch.getTranslationY(), 0);
        } else if (flag == 1) {
            Log.i("tag", "手指上滑，》》》》》》》隐藏");
            mAnimator = ObjectAnimator.ofFloat(groupSearch, "translationY", groupSearch.getTranslationY(),
                    -groupSearch.getHeight());
        }
        animatorSet = new AnimatorSet();
        animatorSet.play(mAnimator);
        animatorSet.start();//开始动画
//        animatorSet.addListener(new Anim);
    }

    @OnClick({R.id.group_search, R.id.create_group})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.group_search:
                break;
            case R.id.create_group:
                Intent intent = new Intent(getContext(), CreateGroupChatActivity.class);
                intent.putExtra(LoongsConfig.topic_id, topic_id);
                startActivity(intent);
                break;
        }
    }

    public void setGender_prefer(String gender_prefer) {
        this.gender_prefer = gender_prefer;
    }

    public void setCity_prefer(String city_prefer) {
        this.city_prefer = city_prefer;
    }

    public void setAge_prefer(String age_prefer) {
        this.age_prefer = age_prefer;
    }

    public void setTopic_id(String topic_id) {
        this.topic_id = topic_id;
    }

    public void startInitData() {
        toolbarAnim(0);//显示
        mShow = true;
        showLoadingDialog();
        data.clear();
        convenGroupListAdapter.notifyDataSetChanged();
        page = 1;
        initdata();
    }

    public void setTopciName(String topicName) {
        this.groupListEt.setText(topicName);
    }
}